<template>
  <a-spin size="large" :spinning="isLoading">
    <div>
      <Selectbox class="select-box" @getData="getDataByCon"/>

    </div>
    <div style="margin-bottom: 16px">
      <a-button
        type="primary"
        :disabled="!hasSelected"
        style="margin-right: 20px"
        @click="comfirmDelete"
      >
        删除所选记录
      </a-button>

      <a-button type="primary" :disabled="!hasSelected" @click="start">
        重新选择
      </a-button>

      <!-- 文字描述 -->
      <span style="margin-left: 8px">
        <template v-if="hasSelected">
          {{ `您已经选择了 ${selectedRowKeys.length} 条日志记录` }}
        </template>
      </span>
    </div>

    <!-- 提示确认窗口 -->
    <a-modal
      title="确认删除"
      cancelText="取消"
      okText="确定"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="visible = false"
    >
      <p>{{ ModalText }}</p>
    </a-modal>

    <a-table
      bordered
      :pagination="pagination"
      :data-source="dataSource"
      rowKey="id"
      :columns="columns"
      :row-selection="{
        columnWidth: '50px',
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
    >
      <!-- 下拉筛选菜单 -->
      <div
        slot="filterDropdown"
        slot-scope="{
          setSelectedKeys,
          selectedKeys,
          confirm,
          clearFilters,
          column,
        }"
        style="padding: 8px; text-align: right"
      >
        <a-input
          v-ant-ref="(c) => (searchInput = c)"
          :placeholder="`Search ${column.dataIndex}`"
          :value="selectedKeys[0]"
          style="width: 188px; margin-bottom: 8px; display: block;"
          @change="
            (e) => setSelectedKeys(e.target.value ? [e.target.value] : [])
          "
          @pressEnter="
            () => handleSearch(selectedKeys, confirm, column.dataIndex)
          "
        />

        <a-button
          type="primary"
          icon="search"
          size="small"
          style="width: 90px; margin-right: 8px"
          @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
        >
          Search
        </a-button>
        <a-button
          size="small"
          style="width: 90px"
          @click="() => handleReset(clearFilters)"
        >
          Reset
        </a-button>
      </div>
      
      <a-icon
        slot="filterIcon"
        slot-scope="filtered"
        type="search"
        :style="{ color: filtered ? '#108ee9' : undefined }"
      />

      <!-- 自定义渲染，渲染数据 -->
      <template slot="customRender" slot-scope="text, record, index, column">
        <span v-if="searchText && searchedColumn === column.dataIndex">
          <template
            v-for="(fragment, i) in text
              .toString()
              .split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))"
          >
            <!-- 高亮显示关键字 -->
            <mark
              v-if="fragment.toLowerCase() === searchText.toLowerCase()"
              :key="i"
              class="highlight"
              >{{ fragment }}</mark
            >
            <!-- 显示非搜索字段的文字 -->
            <template v-else>{{ fragment }}</template>
          </template>
        </span>
        <template v-else>
          {{ text }}
        </template>
      </template>

      <!-- 删除功能按键 -->
      <template slot="operation" slot-scope="text, record">
        <a-popconfirm
          v-if="dataSource.length"
          title="确认删除这条日志记录吗？"
          ok-text="确定"
          cancel-text="取消"
          @confirm="deleteLogger(record.id)"
        >
          <!-- <a href="javascript:;">删除</a> -->
          <button class="operate">删除</button>
        </a-popconfirm>
      </template>
    </a-table>
  </a-spin>
</template>
<script>
import Selectbox from './component/selectbox.vue';
export default {
  inject: ["reload"],
  data() {
    return {
      isLoading: true,
      // 用户信息等
      username: "",
      dataSource: [],
      count: 2,
      columns: [
        {
          title: "用户",
          dataIndex: "username",
          key: "username",

          scopedSlots: {
            // customRender: "username",
            filterDropdown: "filterDropdown",
            filterIcon: "filterIcon",
            customRender: "customRender",
          },
          onFilter: (value, record) =>
            record.username
              .toString()
              .toLowerCase()
              .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: "时间",
          dataIndex: "time",
          key: "time",
          scopedSlots: {
            filterDropdown: "filterTime",
            filterIcon: "filterIcon",
            customRender: "customRender",
          },
          onFilter: (value, record) =>
            record.time
              .toString()
              .toLowerCase()
              .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus();
              });
            }
          },
        },
        {
          title: "设备ID",
          dataIndex: "lockid",
          key: "lockid",
          scopedSlots: {
            filterDropdown: "filterDropdown",
            filterIcon: "filterIcon",
            customRender: "customRender",
          },
          onFilter: (value, record) =>
            record.lockid
              .toString()
              .toLowerCase()
              .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus();
              });
            }
          },
        },
        {
          title: "操作事项",
          dataIndex: "openstate",
          key: "openstate",
          scopedSlots: {
            filterDropdown: "filterDropdown",
            filterIcon: "filterIcon",
            customRender: "customRender",
          },
          onFilter: (value, record) =>
            record.openstate
              .toString()
              .toLowerCase()
              .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus();
              });
            }
          },
        },
        {
          title: "操作结果",
          dataIndex: "success",
          key: "success",
          scopedSlots: {
            filterDropdown: "filterDropdown",
            filterIcon: "filterIcon",
            customRender: "customRender",
          },
          onFilter: (value, record) =>
            record.success
              .toString()
              .toLowerCase()
              .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus();
              });
            }
          },
        },
        {
          title: "删除记录",
          dataIndex: "operation",
          key: "operation",
          scopedSlots: { customRender: "operation" },
        },
      ],
      // 选中的序号
      selectedRowKeys: [],
      // 选中的日志内容
      selectedLoggerList: [],
      // 筛选内容
      searchText: "",
      // 提示弹框
      ModalText: "",
      visible: false,
      confirmLoading: false,

      // 分页组件配置
      pagination: {
        defaultPageSize: 10,
        showTotal: (total) => `共 ${total} 条数据`,
        showSizeChanger: true,
        pageSizeOptions: ["10", "20", "50"],
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize),
      },

      fromTime:{
        year:"1970",
        month:"1",
        day:"1"
      },
      toTime:{
        year:"",
        month:"",
        day:""
      }
    };
  },
  components:{
    Selectbox
  },
  mounted() {
    console.log("logger");
    this.username = this.$_cookie.getCookie("user");
    this.getData();

    const date = new Date();
    this.toTime.year = date.getFullYear();
    this.toTime.month = date.getMonth() + 1;
    this.toTime.day = date.getDate();

  },
  computed: {
    hasSelected() {
      return this.selectedRowKeys.length > 0;
    },
  },
  methods: {
    // 日期格式转化--传入date对象
    dateFormat(date) {
      const year = date.getFullYear();
      const month = date.getMonth();
      const day = date.getDate();
      return year + "/" + (month + 1) + "/" + day;
    },
    // 获取全部日志数据
    async getData() {
      const data = {
        username: this.username,
        identityId: undefined,
        timeStart: undefined,
        timeEnd: undefined,
        current: 1,
        limit: 5000,
      };
      const res = await this.$_api.getAllLoggers(data);
      let dataResponce = res.data.data.list.records;
      this.dataSource = this.handleData(dataResponce);
      if (res.data.code === 20000) {
        this.isLoading = false;
      }
    },

    // 根据条件获取日志
    async getDataByCon(value){
      this.isLoading = true;
      const condition = value;
      const data = {
        username: this.username,
        identityId: condition.identityId ? condition.identityId : undefined,
        timeStart: condition.timestart ? condition.timestart : undefined,
        timeEnd: condition.timeend ? condition.timeend: undefined,
        current: 1,
        limit: 10000,
      };
      const res = await this.$_api.getAllLoggers(data);
      let dataResponce = res.data.data.list.records;
      this.dataSource = this.handleData(dataResponce);
      if (res.data.code === 20000) {
        this.isLoading = false;
      }
    },

    // 数据处理
    handleData(data) {
      // 时间倒序处理
      for (let i = 0, j = data.length - 1; i < j; ++i, --j) {
        var t = data[i];
        data[i] = data[j];
        data[j] = t;
      }
      // TODO:时间格式处理
      for (let i = 0; i < data.length; i++) {
        // 转换状态
        if (data[i].openstate == 0) {
          data[i].openstate = "进行关锁操作";
        } else if (data[i].openstate == 1) {
          data[i].openstate = "进行开锁操作";
        } else {
          this.$message.infp("ERROR!");
        }
        if (data[i].success == 0) {
          data[i].success = "操作失败";
        } else if (data[i].success == 1) {
          data[i].success = "操作成功";
        }
      }
      return data;
    },
    // 删除日志逻辑
    async delete(id) {
      const data = { id };
      const res = await this.$_api.delLogger(data);
      return res.data.success;
    },

    // 删除日志，单个
    async deleteLogger(loggerId) {
      const res = await this.delete(loggerId);
      this.$message.info({
        duration: 1,
        content: "正在删除...",
      });
      if (res) {
        setTimeout(() => {
          this.$message.success("删除成功");
          this.reload();
        }, 1000);
      }
    },
    // 删除日志，多选
    deleteLoggers() {
      if (this.selectedLoggerList.length > 0) {
        for (let i = 0; i < this.selectedLoggerList.length; i++) {
          const loggerId = this.selectedLoggerList[i].id;
          this.delete(loggerId);
        }
      }
    },
    // 提示窗口
    handleOk(e) {
      this.ModalText = "正在删除...";
      this.deleteLoggers();
      this.confirmLoading = true;
      setTimeout(() => {
        this.visible = false;
        this.confirmLoading = false;
        this.$message.success(
          "成功删除" + this.selectedRowKeys.length + "条日志记录"
        );
        this.reload();
      }, 1000);
    },
    handleCancel(e) {
      this.visible = false;
    },
    // 确认删除与否
    comfirmDelete() {
      this.ModalText =
        "确认删除这" +
        this.selectedRowKeys.length +
        "条日志记录吗？删除后将不可恢复！";
      this.visible = true;
    },

    // filterTime
    filterTime(){

    },
    // 普通筛选板块，确认筛选
    // selectedKeys--关键字；
    // confirm--回调函数；
    // dataIndex--关键字段
    handleSearch(selectedKeys, confirm, dataIndex) {
      confirm();
      this.searchText = selectedKeys[0];
      this.searchedColumn = dataIndex;
    },
    // 筛选板块，重置
    handleReset(clearFilters) {
      clearFilters();
      this.searchText = "";
    },

    // 多选板块，重置
    start() {
      this.selectedRowKeys = [];
    },
    // 跟选择有关的方法
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedLoggerList = selectedRows;
    },
  },
};
</script>
<style lang="less" scope>
.editable-cell {
  position: relative;
}

.editable-cell-input-wrapper,
.editable-cell-text-wrapper {
  padding-right: 24px;
}

.editable-cell-text-wrapper {
  padding: 5px 24px 5px 5px;
}

.editable-cell-icon,
.editable-cell-icon-check {
  position: absolute;
  right: 0;
  width: 20px;
  cursor: pointer;
}

.editable-cell-icon {
  line-height: 18px;
  display: none;
}

.editable-cell-icon-check {
  line-height: 28px;
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}

.editable-cell-icon:hover,
.editable-cell-icon-check:hover {
  color: #108ee9;
}

.editable-add-btn {
  margin-bottom: 8px;
}
.two-side {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 10px;
  margin-bottom: 10px;
  padding-left: 10px;
}
.filter-time {
  padding: 10px;
  width: 280px;
  height: 130px;
}
.input-time {
  display: inline-block;
  width: 60px;
  text-align: right;
}
.input-temp {
  margin-bottom: 10px;
}
.select-box{
  margin: 15px 0;
}
.operate{
  border: none;
  color: white;
  background: #4396f5;
  border-radius: 5px;
  outline: none;
  padding: 4px 10px;

  transition: background 0.5s;
  &:hover{
    cursor: pointer;
    background: #0066da;
  }
}
</style>
